package com.kizuki.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * fastjson正常使用需要bean有
 * Getter
 * Setter
 * NoArgsConstructor
 */
public class TestFastjson {

    private static List<People> list = new ArrayList<>();

    static {
        list.add(new People(10, "李白", 100, new Date()));
        list.add(new People(11, "李黑", 200, new Date()));
    }

    @Test
    public void testJsonObject() {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < 2; i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("AGE", 10);
            jsonObject.put("FULL NAME", "Doe " + i);
            jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
            jsonArray.add(jsonObject);
        }
        String jsonOutput = jsonArray.toJSONString();
        System.out.println(jsonOutput);
    }

    @Test
    public void testToJsonString() {
        String json = JSON.toJSONString(list);
        String jsons = JSON.toJSONString(list, SerializerFeature.BeanToArray);
        System.out.println(json);
        System.out.println(jsons);
    }

    @Test
    public void testParse() {
        People libai = new People(10, "libai", 100, new Date());
        String json = JSON.toJSONString(libai);
        People p = JSON.parseObject(json, People.class);
        System.out.println("libai = " + p);

        List<People> people = JSON.parseArray(JSON.toJSONString(list), People.class);
        people.forEach(System.out::println);
    }

}
